import React, {useEffect, useState, forwardRef, useImperativeHandle} from 'react';
import PageModule from '@/components/PageModule.tsx'
import {Button, Col, Form, Cascader, Row} from "antd";
import CycleForm from "@/components/DynamicSearchForm/CycleForm.tsx";
import {getOrganizationForLogged} from '@/utils/organization.ts'
import {useSelector} from 'react-redux'
import {
    companyCodeQueryOrgList,
    queryAllCompany,
    queryAllProjectList,
    verifyCarPolicyCode
} from "@/axios/apis.ts";
import {onlyNumberLast2Digits, onlyNumberLast4Digits} from "@/utils/regular.ts";
import {findIByCodeRecursion, formatFormDayJs, formatToDayJs} from "@/utils/index.ts";

interface CarBasicInfoProps {
    carBasicInfo: object
}

const BasicInfoDate = ['insuranceDate', 'valiDate', 'endDate']

const CarBasicInfo = forwardRef((props, ref) => {
    let {carBasicInfo, setProjectCode, policyDisabled} = props
    useImperativeHandle(ref, () => ({
        verifyTheForm: () => {
            return new Promise((resolve, reject) => {
                basicForm.validateFields().then((values) => {
                    formatFormDayJs(BasicInfoDate, values)
                    const project = formFields[0].options.find(item => item.projectCode === values.projectCode)
                    values.projectName = project?.name
                    values.projectType = project?.type
                    const org = findIByCodeRecursion(formFields[1].options, values.orgCode,'orgChildrenMap')
                    if (org) {
                        values.orgName = org.orgName
                        values.orgPath = org.orgPath
                    }
                    values.companyName = formFields[3].options.find(item => item.companyCode === values.companyCode)?.name
                    const comOrg = findIByCodeRecursion(formFields[4].options, values.companyOrgCode,'childOrgMap')
                    if (comOrg){
                        values.companyOrgName = comOrg.orgName
                        values.companyOrgPath = comOrg.orgPath
                    }
                    resolve(values)
                }).catch((err) => {
                    reject({})
                })
            })
        }
    }));
    const [basicForm] = Form.useForm();
    const {userInfo} = useSelector(state => state.userSlice);
    const [formFields, setFormFields] = useState([
        {
            type: 'select',
            name: 'projectCode',
            label: '项目名称',
            placeholder: '请选择',
            options: [],
            rules: [{required: true, message: '请选择项目名称'}],
            fieldNames: {
                label: 'name',
                value: 'projectCode'
            },
            onChange: (value) => {
                setProjectCode(value)
            }
        },
        {
            type: 'cascader',
            name: 'orgCode',
            label: '机构名称',
            placeholder: '请选择',
            options: [],
            fieldNames: {
                label: 'orgName', value: 'orgCode', children: 'orgChildrenMap'
            },
            rules: [{required: true, message: '请选择机构名称'}]
        },
        {
            type: 'input',
            name: 'policyNo',
            label: '保单号',
            placeholder: '请输入',
            rules: [
                {required: true, message: '请输入保单号'},
                {
                    validator: (_, value) => {
                        if (!value) return Promise.reject(new Error(''));
                        if (!/^[a-zA-Z0-9\-/]+$/.test(value)) {
                            return Promise.reject(new Error('仅限录入“字母”、“数字”、“-”、“/”'));
                        }
                        return new Promise((resolve, reject) => {
                            verifyCarPolicyCode({
                                policyNo: value,
                                // applyId: localStorage.getItem("fromId")
                            }).then(res => {
                                if (+res.code === 200) {
                                    resolve()
                                } else {
                                    console.log(res.msg)
                                    reject(new Error(res.msg));
                                }
                            }).catch(err => {
                                resolve()
                            })
                        });
                    }
                }]
        },
        {
            type: 'select',
            name: 'companyCode',
            label: '保险公司',
            placeholder: '请选择',
            options: [],
            fieldNames: {
                label: 'name',
                value: 'companyCode'
            },
            onChange: (value) => {
                if (!value) {
                    return
                }
                getOrgList()
            },
            rules: [{required: true, message: '请选择保险公司'}]
        },
        {
            type: 'cascader',
            name: 'companyOrgCode',
            label: '保险公司分支机构',
            placeholder: '请选择',
            options: [],
            fieldNames: {
                label: 'orgName', value: 'orgCode', children: 'childOrgMap'
            },
            rules: [{required: true, message: '请选择保险公司分支机构'}],
        },
        {
            type: 'date',
            name: 'insuranceDate',
            label: '投保日期',
            rules: [{required: true, message: '请选择投保日期'}]
        },
        {
            type: 'date',
            name: 'valiDate',
            label: '保单生效日期',
            rules: [{required: true, message: '请选择保单生效日期'}]
        },
        {
            type: 'date',
            name: 'endDate',
            label: '保单失效日期',
            rules: [{required: true, message: '请选择保单失效日期'}]
        },
        {
            type: 'input',
            name: 'amount',
            label: '总保额',
            placeholder: '请输入',
            rules: [{required: true, message: '请输入总保额'}, {validator: onlyNumberLast2Digits}]
        },
        {
            type: 'input',
            name: 'taxPremium',
            label: '含税总保费',
            placeholder: '请输入',
            rules: [{required: true, message: '请输入含税总保费'}, {validator: onlyNumberLast2Digits}]
        },
        {
            type: 'input',
            name: 'premium',
            label: '净保费',
            placeholder: '请输入',
            rules: [{required: true, message: '请输入净保费'}, {validator: onlyNumberLast2Digits}]
        },
        {
            type: 'input',
            name: 'commisionRateByAgree',
            label: '应收佣金比例（%）',
            placeholder: '请输入',
            rules: [{required: true, message: '请输入应收佣金比例'}, {validator: onlyNumberLast4Digits}]
        },
        {
            type: 'input',
            name: 'commisionFeeByAgree',
            label: '应收佣金金额',
            placeholder: '请输入',
            rules: [{required: true, message: '请输入应收佣金金额'}, {validator: onlyNumberLast2Digits}]
        },])
    const getSelectList = () => {
        Promise.all([
            getOrganizationForLogged(userInfo.powers),
            queryAllCompany(),
            queryAllProjectList({
                isPower: true,
                userInfoString: JSON.stringify(userInfo),
            })
        ]).then(res => {
            const [res1, res2, res3] = res
            const newArray = [...formFields];
            newArray[0].options = res3.data
            newArray[1].options = res1.data
            newArray[3].options = res2.data
            setFormFields(newArray)
        })
    }
    const getOrgList = () => {
        if (!basicForm.getFieldValue('companyCode')) return
        companyCodeQueryOrgList({companyCode: basicForm.getFieldValue('companyCode')}).then(res => {
            if (+res.code === 200) {
                const newArray = [...formFields];
                newArray[4].options = res.data
                setFormFields(newArray)
            }
        })
    }
    useEffect(() => {
        getSelectList()
    }, []);
    useEffect(() => {
        getOrgList()
        // 下面是具体的逻辑
    }, [basicForm.getFieldValue('companyCode')])
    useEffect(() => {
        if (carBasicInfo) {
            formatToDayJs(BasicInfoDate, carBasicInfo)
            basicForm.setFieldsValue(carBasicInfo)
        }
    }, [carBasicInfo]);
    return (
        <PageModule title="基本信息">
            <Form
                layout="horizontal"
                autoComplete="off"
                labelCol={{span: 8}}
                wrapperCol={{span: 16}}
                form={basicForm}
                disabled={policyDisabled}
            >
                <Row>
                    <CycleForm fields={formFields} disabled={policyDisabled}/>
                </Row>
            </Form>
        </PageModule>
    );
});

export default CarBasicInfo;